A dieter consumes calories[i] calories on the i-th day. For every consecutive sequence of k days, they look at T, the total calories consumed during that sequence of k days:
If T < lower, they performed poorly on their diet and lose 1 point;
If T > upper, they performed well on their diet and gain 1 point;
Otherwise, they performed normally and there is no change in points.
Return the total number of points the dieter has after all calories.length days.
Note that: The total points could be negative.
Example 1:
Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
Output: 0
Explaination: calories[0], calories[1] < lower and calories[3], calories[4] > upper, total points = 0.
Example 2:
Input: calories = [3,2], k = 2, lower = 0, upper = 1
Output: 1
Explaination: calories[0] + calories[1] > upper, total points = 1.
Example 3:
Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
Output: 0
Explaination: calories[0] + calories[1] > upper, calories[2] + calories[3] < lower, total points = 0.
此題要求從一個數字陣列(chlories[])中逐一以k天為一組,將其k天的calorie總和分別與lower及upper相比,若該k天之和小於lower則減一分,若大於upper則加一分,最後計算其總分。
class Solution {
public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
int len = calories.length, sum = 0;
for(int i = 0; i+k-1 < len; i++){
int temp = 0;
for (int j=0; j<k; j++){
temp += calories[i+j];
}
if(temp < lower){
sum--;
}
if(temp > upper){
sum++;
}
}
return sum;
}
}
此題是LeetCode Contest的題目,難度為簡單,但應該有更好的解法。
希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。